package jlxy.ise.eroad;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * 增加对Spring boot微服务的测试
 *
 * @author yecq
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public abstract class SpringBootTestBase {

    @Autowired
    protected TestRestTemplate restTemplate;

    // 执行url，返回http状态
    protected int execGet(String url, Map<String, Object> param, Object... v) {
        if (param != null && !param.isEmpty()) {
            url += "?" + condition2ParamEncoded(param);
        }
        return this.restTemplate.getForEntity(url, String.class, v).getStatusCodeValue();
    }

    protected int execGet(String url, Object... v) {
        return execGet(url, null, v);
    }

    private String condition2ParamEncoded(Map<String, Object> condition) {
        String ret = "";
        Iterator<Entry<String, Object>> ite = condition.entrySet().iterator();
        while (ite.hasNext()) {
            Entry<String, Object> ent = ite.next();
            String ori = (String) ent.getValue();
            try {
                ori = URLEncoder.encode(ori + "", "utf-8");
            } catch (UnsupportedEncodingException ex) {

            }
            ret += ent.getKey().trim() + "=" + ori + "&";
        }
        return ret.substring(0, ret.length() - 1);
    }

    protected int execPost(String url, Map<String, Object> param, Object... v) {
        MultiValueMap<String, String> map = getMultiValueFromMap(param);
        return this.restTemplate.postForEntity(url, map, String.class, v).getStatusCodeValue();
    }

    protected int execPost(String url, Object... v) {
        return execPost(url, null, v);
    }

    private MultiValueMap<String, String> getMultiValueFromMap(Map<String, Object> param) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap();
        if (param == null) {
            return map;
        }

        Iterator<Entry<String, Object>> ite = param.entrySet().iterator();
        while (ite.hasNext()) {
            Entry<String, Object> ent = ite.next();
            map.add(ent.getKey(), ent.getValue() + "");
        }
        return map;
    }
}
